#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::unique_ptr;
using std::shared_ptr;

class Point
{
public:
    Point(int x,int y)
        : _ix(x)
          , _iy(y)
    {}

    void print() const{
        cout << "(" << _ix
            << "," << _iy
            << ")" << endl;
    }
private:
    int _ix;
    int _iy;
};

void test0(){
    //需要人为避免
    Point * pp = new Point(1,2);
    unique_ptr<Point> up(pp);
    unique_ptr<Point> up2(pp);
}

void test1(){
    //推荐的写法
    unique_ptr<Point> up(new Point(1,2));
    unique_ptr<Point> up2(new Point(1,2));
    up->print();
    up2->print();

    //也需要人为避免
    /* up.reset(up2.get()); */
    /* cout << up.get() << endl; */
    /* cout << up2.get() << endl; */
}

void test2(){
    //用同一个裸指针初始化多个shared_ptr对象也是不行的
    Point * pp = new Point(1,2);
    shared_ptr<Point> sp(pp);
    shared_ptr<Point> sp2(pp);

    //复制或赋值的方式才是合法共享的方式
    /* shared_ptr<Point> sp2(sp); */
    sp->print();
    sp2->print();
    cout << sp.use_count() << endl;
    cout << sp2.use_count() << endl;
}

void test3(){
    //使用不同的智能指针托管同一片堆空间
    shared_ptr<Point> sp(new Point(1,2));
    shared_ptr<Point> sp2(new Point(1,2));
    sp.reset(sp2.get());
}

int main(void){
    test3();
    return 0;
}
